/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.infor.web;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.fee.entity.Profit;
import com.jeeplus.modules.fee.service.ProfitService;
import com.jeeplus.modules.infor.entity.*;
import com.jeeplus.modules.infor.service.*;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;

/**
 * 装卸利润分析Controller
 * @author 李超辉
 * @version 2018-09-27
 */
@Controller
@RequestMapping(value = "${adminPath}/infor/loading")
public class LoadingController extends BaseController {

	@Autowired
	private LoadingService loadingService;
	@Autowired
	private ProfitAnalysisService profitAnalysisService;
	@Autowired
	private JdbcTemplate jdbc;
	@Autowired
	private ProfitService profitService;
	@Autowired
	private RentPriceService rentPriceService;
	@Autowired
	private PositionService positionService;
	@Autowired
	private LoadingBottomService loadingBottomService;
	@Autowired
	private LoadingIncomeService loadingIncomeService;
	@Autowired
	private LoadingOutService loadingOutService;
	@ModelAttribute
	public Loading get(@RequestParam(required=false) String id) {
		Loading entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = loadingService.get(id);
		}
		if (entity == null){
			entity = new Loading();
		}
		return entity;
	}
	/**
	 * 利润分析总表列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "cx")
	public String cx(Date min, Date max, String pro) {
		jdbc.execute("delete from infor_loading");
		Calendar c = Calendar.getInstance();
		DecimalFormat df = new DecimalFormat("0.00%");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		NumberFormat nf = NumberFormat.getInstance();
		Date i=min;
		Date mixx;
		while (i.getTime()<max.getTime()) {
			mixx=i;
			Loading loading=new Loading();
			loading.setDate(i);
			c.setTime(i);
			c.add(Calendar.MONTH, 1);
			i=c.getTime();
			//装卸收入
			String poj;
			if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
				poj=pro;
			}else if(!UserUtils.getUseroffice().equals("总部")){
				poj=UserUtils.getUseroffice();
			}else{
				poj=UserUtils.getUseroffice();
			}
			List<Map<String,Object>> maps=ck(format.format(mixx),poj);
			List<Map<String,Object>> map=rk(format.format(mixx),poj);
			double zxzc=0.0;
			double zxsr=0.0;
			double ck=0.0;
			double rk=0.0;
			double sr=0.0;
			double bd=0.0;
			double dw=0.0;
			for(Map<String,Object>m:maps){
				if(positionService.get(m.get("position")+"").getName().contains("装卸")){
					dw+=Double.parseDouble(m.get("amount")+"");
					LoadingIncome loadingIncome=new LoadingIncome();
					loadingIncome.setPro(m.get("pro")+"");
					loadingIncome.setMin(mixx);
					loadingIncome.setMax(mixx);
					List<LoadingIncome> ins=loadingIncomeService.findList(loadingIncome);
					if(ins!=null&&ins.size()>0){
						loadingIncome=ins.get(0);
						String ad=loadingIncome.getAd();
						String sl=loadingIncome.getSl();
						String pri=loadingIncome.getOu();
						zxsr+=Double.parseDouble(m.get("amount")+"")*(Double.parseDouble(pri)+Double.parseDouble(ad))*(Double.parseDouble(sl)+1);
						sr+=Double.parseDouble(m.get("amount")+"")*(Double.parseDouble(pri)+Double.parseDouble(ad));

					}else{
						jdbc.execute("delete from infor_loading");
						return "income";
					}
				}
				LoadingBottom l=new LoadingBottom();
				l.setPosition(positionService.get(m.get("position")+"").getName());
				l.setPro(m.get("pro")+"");
				l.setMax(mixx);
				l.setMin(mixx);
				List<LoadingBottom> li=loadingBottomService.findList(l);
				if(li.size()>0&&li!=null){
					bd+=Double.parseDouble(li.get(0).getPrice());
					zxzc+=Double.parseDouble(li.get(0).getPrice());
					for(Map<String,Object>ma:map){
						if((m.get("pro")+"").equals(ma.get("pro")+"")&&(m.get("position")+"").equals(ma.get("position")+"")&&(m.get("name")+"").equals(ma.get("name")+"")){
							map.remove(ma);
						}

					}
					continue;
				}

				LoadingOut loadingOut=new LoadingOut();
				loadingOut.setGtype(m.get("gtype")+"");
				loadingOut.setPosition(positionService.get(m.get("position")+"").getName());
				loadingOut.setPro(m.get("pro")+"");
				loadingOut.setType("出库");
				loadingOut.setMin(mixx);
				loadingOut.setMax(mixx);
				List<LoadingOut> outs=loadingOutService.findList(loadingOut);
				if(outs!=null&&outs.size()>1){
					ck+=Double.parseDouble(outs.get(0).getPrice())* Double.parseDouble(m.get("amount")+"");
					zxzc+=Double.parseDouble(outs.get(0).getPrice())* Double.parseDouble(m.get("amount")+"");
				}else{
					jdbc.execute("delete from infor_loading");
					return "zx";
				}

			}

			for(Map<String,Object>m:map){
				if(positionService.get(m.get("position")+"").getName().contains("装卸")){
					dw+=Double.parseDouble(m.get("amount")+"");
					LoadingIncome loadingIncome=new LoadingIncome();
					loadingIncome.setPro(m.get("pro")+"");
					loadingIncome.setMin(mixx);
					loadingIncome.setMax(mixx);
					List<LoadingIncome> ins=loadingIncomeService.findList(loadingIncome);
					if(ins!=null&&ins.size()>0){
						loadingIncome=ins.get(0);
						String ad=loadingIncome.getAd();
						String sl=loadingIncome.getSl();
						String pri=loadingIncome.getPu();
						sr+=Double.parseDouble(m.get("amount")+"")*(Double.parseDouble(pri)+Double.parseDouble(ad));
						zxsr+=Double.parseDouble(m.get("amount")+"")*(Double.parseDouble(pri)+Double.parseDouble(ad))*(Double.parseDouble(sl)+1);
					}
				}

				LoadingBottom l=new LoadingBottom();
				l.setPosition(positionService.get(m.get("position")+"").getName());
				l.setPro(m.get("pro")+"");
				l.setMax(mixx);
				l.setMin(mixx);
				List<LoadingBottom> li=loadingBottomService.findList(l);
				if(li.size()>0&&li!=null){
					bd+=Double.parseDouble(li.get(0).getPrice());
					zxzc+=Double.parseDouble(li.get(0).getPrice());
					continue;
				}

				LoadingOut loadingOut=new LoadingOut();
				loadingOut.setGtype(m.get("gtype")+"");
				loadingOut.setPosition(positionService.get(m.get("position")+"").getName());
				loadingOut.setPro(m.get("pro")+"");
				loadingOut.setType("入库");
				loadingOut.setMin(mixx);
				loadingOut.setMax(mixx);
				List<LoadingOut> outs=loadingOutService.findList(loadingOut);
				if(outs!=null&&outs.size()>1){
					zxzc+=Double.parseDouble(outs.get(0).getPrice())* Double.parseDouble(m.get("amount")+"");
					rk+=Double.parseDouble(outs.get(0).getPrice())* Double.parseDouble(m.get("amount")+"");
				}else{
					jdbc.execute("delete from infor_loading");
					return "zx";
				}

			}
			loading.setBdzc(nf.format(bd).replaceAll(",",""));
			loading.setRkzc(nf.format(rk).replaceAll(",",""));
			loading.setCkzc(nf.format(ck).replaceAll(",",""));
			loading.setZzc(nf.format(zxzc).replaceAll(",",""));
			loading.setDw(nf.format(dw).replaceAll(",",""));
			loading.setSr(nf.format(sr).replaceAll(",",""));
			loading.setSrhs(nf.format(zxsr).replaceAll(",",""));
			double mlr=zxsr-zxzc;
			loading.setMlr(nf.format(mlr).replaceAll(",",""));
			loading.setLrl(df.format(mlr/zxsr));
			loadingService.save(loading);
		}

		return "success";
	}
	public List<Map<String,Object>> rk(String min,String pro){
		String sql;

		if(!pro.equals("总部")){
			sql = "SELECT p.pro as pro, p.position AS position,p.name as name,p.gtype AS gtype,SUM(p.workload) AS amount FROM `wms_statistics` p WHERE   DATE_FORMAT('"+min+"','%Y%m')=DATE_FORMAT(p.create_date,'%Y%m')  and p.pro='" + pro + "'   GROUP BY p.pro,p.name, p.position,p.gtype";
		}else{
			sql = "SELECT p.pro as pro, p.position AS position,p.name as name, p.type AS type,p.gtype AS gtype,SUM(p.workload) AS amount FROM `wms_statistics` p WHERE DATE_FORMAT('"+min+"','%Y%m')=DATE_FORMAT(p.create_date,'%Y%m')  GROUP BY p.name,p.position,p.gtype ";
		}
		List<Map<String,Object>> list=jdbc.queryForList(sql);
		return  list;
	}
	public List<Map<String,Object>> ck(String min,String pro){
		String sq;
		if(!pro.equals("总部")){
			sq = "SELECT p.pro as pro, p.position AS position,p.name as name, p.gtype AS gtype,SUM(p.work) AS amount FROM `wms_outstatistics` p WHERE DATE_FORMAT('"+min+"','%Y%m')=DATE_FORMAT(p.create_date,'%Y%m') and p.pro='" + pro + "'   GROUP BY  p.pro,p.name, p.position,p.gtype";
		}else{
			sq = "SELECT p.pro as pro, p.position AS position,p.name as name, p.type AS type,p.gtype AS gtype,SUM(p.work) AS amount FROM `wms_outstatistics` p WHERE DATE_FORMAT('"+min+"','%Y%m')=DATE_FORMAT(p.create_date,'%Y%m'))  GROUP BY p.name,p.p.position,p.gtype";
		}
		List<Map<String,Object>> lis=jdbc.queryForList(sq);
		return  lis;
	}
	/**
	 * 装卸利润分析列表页面
	 */
	@RequiresPermissions("infor:loading:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/infor/loadingList";
	}
	
		/**
	 * 装卸利润分析列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:loading:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Loading loading, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Loading> page = loadingService.findPage(new Page<Loading>(request, response), loading); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑装卸利润分析表单页面
	 */
	@RequiresPermissions(value={"infor:loading:view","infor:loading:add","infor:loading:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Loading loading, Model model) {
		model.addAttribute("loading", loading);
		return "modules/infor/loadingForm";
	}

	/**
	 * 保存装卸利润分析
	 */
	@ResponseBody
	@RequiresPermissions(value={"infor:loading:add","infor:loading:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Loading loading, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, loading)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		loadingService.save(loading);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存装卸利润分析成功");
		return j;
	}
	
	/**
	 * 删除装卸利润分析
	 */
	@ResponseBody
	@RequiresPermissions("infor:loading:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Loading loading, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		loadingService.delete(loading);
		j.setMsg("删除装卸利润分析成功");
		return j;
	}
	
	/**
	 * 批量删除装卸利润分析
	 */
	@ResponseBody
	@RequiresPermissions("infor:loading:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			loadingService.delete(loadingService.get(id));
		}
		j.setMsg("删除装卸利润分析成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("infor:loading:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Loading loading, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "装卸利润分析"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Loading> page = loadingService.findPage(new Page<Loading>(request, response, -1), loading);
    		new ExportExcel("装卸利润分析", Loading.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出装卸利润分析记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("infor:loading:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Loading> list = ei.getDataList(Loading.class);
			for (Loading loading : list){
				try{
					loadingService.save(loading);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条装卸利润分析记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条装卸利润分析记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入装卸利润分析失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/loading/?repage";
    }
	
	/**
	 * 下载导入装卸利润分析数据模板
	 */
	@RequiresPermissions("infor:loading:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "装卸利润分析数据导入模板.xlsx";
    		List<Loading> list = Lists.newArrayList(); 
    		new ExportExcel("装卸利润分析数据", Loading.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/loading/?repage";
    }

}